package com.general.seckill.stockservice.rocketmq;

import com.general.seckill.stockservice.StockService;
import com.general.seckill.stockservice.request.StockDecreaseDTO;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @description: SecKillEventConsumer
 * @author: general
 * @version: 1.0
 * @create: 2022-04-30 18:46
 **/
@Service
@RocketMQMessageListener(topic = "${demo.rocketmq.topic.second-kill}", consumerGroup = "stock-service-consumer")
public class SecKillEventConsumer implements RocketMQListener<SecKillEntity>, RocketMQPushConsumerLifecycleListener {

    @Resource
    private StockService stockService;

    @Override
    public void onMessage(SecKillEntity secKillEntity) {
        // todo  redis扣减库存
        // todo  扣减之后 生产订单
        System.out.println("secKillEntity = " + secKillEntity);

        StockDecreaseDTO decreaseDTO = new StockDecreaseDTO();
        decreaseDTO.setProductId(secKillEntity.getProductId());
        decreaseDTO.setUserId(secKillEntity.getUserId());
        decreaseDTO.setNum(1);
        stockService.decreaseStock(decreaseDTO);
    }

    @Override
    public void prepareStart(DefaultMQPushConsumer consumer) {
        // 设置最大重试次数
        consumer.setMaxReconsumeTimes(1);
//        // 如下，设置其它consumer相关属性
//        consumer.setPullBatchSize(16);
    }
}
